package com.example.bledemo

import android.bluetooth.BluetoothDevice
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView

class BleAdapter(
    private val context: Context,
    private val devices: List<BluetoothDevice>,
    private val rssis: List<Int>
    ): BaseAdapter() {

    class BleViewHolder(view: View) {
        val name: TextView = view.findViewById(R.id.name)
        val introduce: TextView = view.findViewById(R.id.introduce)
        val tvRssi: TextView = view.findViewById(R.id.rssi)
    }
    override fun getCount() = devices.size

    override fun getItem(position: Int) = devices[position]

    override fun getItemId(position: Int) = 0L

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? {
        var convertView = convertView
        val viewHolder: BleViewHolder
        if (convertView == null) {
            convertView = LayoutInflater.from(context)
                    .inflate(R.layout.bluetooth_devices_list_item, null)
            viewHolder = BleViewHolder(convertView!!)
            convertView!!.setTag(viewHolder)
        } else {
            viewHolder = convertView.tag as BleViewHolder
        }
        val device = getItem(position)
        viewHolder.name.text = device.name
        viewHolder.introduce.text = device.address
        viewHolder.tvRssi.text = rssis[position].toString()
        return convertView
    }

}